<?php

namespace app\stores\controller\miniapp;

use app\BaseController;
use app\beautiful\model\LevelBenefitsModel;
use app\beautiful\model\LevelModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\PartnerModel;
use app\beautiful\model\setting\LevelSettingModel;
use app\stores\logic\MemberWalletLogic;
use app\stores\logic\order\OrderLogic;
use app\stores\model\member\MemberLevelModel;
use app\stores\model\order\LevelOrderModel;
use think\facade\Db;

class Level extends BaseController{

    public function index()
    {
        //充值会员直接在后台充值
        $select_setting = LevelSettingModel::where(['shop_id'=>$this->request->shopId,'is_selected'=>1,'type'=>2])->find();
        if(empty($select_setting) || $select_setting->type<1) return $this->success([]);
        $where['type']=$select_setting->type;
        $where['shop_id']=$this->request->shopId;
        $model = new LevelModel();
        $return = $model->getList($where,['l.add_time'=>'desc'],$this->request->page,$this->request->limit,'l.time_type,l.level_id,l.name,l.price,l.discount_force,lb.num,c.name as coupon_name,c.coupon_money');
        $return['open_type'] = $select_setting['open_type']?explode(',',$select_setting['open_type']):$select_setting['open_type'];
        $return['time_type'] = $select_setting['time_type'];
        return $this->success($return);

    }
    /*付费会员*/
    public function createOrder(){
        $level_id = $this->request->param('level_id/d',0);
        $mix_pay_type = $this->request->param('mix_pay_type');
        Db::startTrans();

        try{

            $order_logic = OrderLogic::init($this->request->shopId);

            $order_id=$order_logic['pay_order']->createOrder(['level_id'=>$level_id,'member_id'=>$this->request->memberId,'mix_pay_type'=>$mix_pay_type]);

            Db::commit();

            return $this->success(['order_id'=>$order_id]);

        } catch (\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }

    /*钱包支付（不存在待支付需要去支付的情况）*/
    public function platformMoneyPay()

    {

        $order_id = $this->request->param('order_id/d');
        $mix_pay_type = $this->request->param('mix_pay_type');
        if(empty($order_id)){

            return $this->error('请选择要支付的订单');

        }

        if( null === $order = LevelOrderModel::find($order_id)){

            return $this->error('订单不存在');

        }

        if($order->status != 0){

            return $this->error('订单不在未支付状态');

        }

        $time = time() - 1800;//订单30分钟

        if(strtotime($order->add_time) < $time){ //如果 订单超过30分钟则不能支付了

            return $this->error('订单支付已经超时了，不能继续支付');

        }

        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){

            return $this->error('订单不存在');

        }
        $level_model = new LevelModel();

        $level = $level_model->getById(['level_id'=>$order->level_id,'is_delete'=>0]);

        if(empty($level)) return  $this->error('等级不存在');

        Db::startTrans();

        try{

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);

            $needPay = sprintf("%.2f",$order->pay_money);

            if($needPay <= 0){

                Db::rollback();

                return $this->error('支付金额不正确');

            }

            $order->is_paid = 1;

            $order->pay_time = date('Y-m-d H:i:s');

            $order->status = 1;

            $order->pay_type = 'platform_money';

            if(empty($mix_pay_type)) $order->platform_money = $order->pay_money;

            $order->save();

            if(!empty($mix_pay_type)){
                $return = mix_pay_money($order,'',3);
                if($return['error']){
                    Db::rollback();
                    return $this->error($return['error']);
                }
            }else {
                $StoresMemberWalletLogic = new \app\stores\logic\MemberWalletLogic($this->request->shopId, $this->request->memberId);

                $res = $StoresMemberWalletLogic->usePlatformMoney($needPay, 0, 0, 0, 25,$order->order_id); //商城购物使用

                if ($res == false) {

                    Db::rollback();

                    return $this->error($MemberWalletLogic->getError());

                }
            }
           //修改会员有效时间
            $return = memberVipTime($order);
            if(!$return['code']){
                return  $this->error($return['error']);
            }

            //领券
            memberVipCoupon($order,$level);

            Db::commit();

            return $this->success('钱包支付成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }
    /*储值卡支付（不存在待支付需要去支付的情况）*/
    public function moneyPay()

    {

        $order_id = $this->request->param('order_id/d');
        $mix_pay_type = $this->request->param('mix_pay_type');
        if(empty($order_id)){

            return $this->error('请选择要支付的订单');

        }

        if( null === $order = LevelOrderModel::find($order_id)){

            return $this->error('订单不存在');

        }

        if($order->status != 0){

            return $this->error('订单不在未支付状态');

        }

        $time = time() - 1800;//订单30分钟

        if(strtotime($order->add_time) < $time){ //如果 订单超过30分钟则不能支付了

            return $this->error('订单支付已经超时了，不能继续支付');

        }

        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){

            return $this->error('订单不存在');

        }

        $level_model = new LevelModel();

        $level = $level_model->getById(['level_id'=>$order->level_id,'is_delete'=>0]);

        if(empty($level)) return  $this->error('等级不存在');

        Db::startTrans();

        try{

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);

            $needPay = sprintf("%.2f",$order->pay_money);

            if($needPay <= 0){

                Db::rollback();

                return $this->error('支付金额不正确');

            }

            $order->is_paid = 1;

            $order->pay_time = date('Y-m-d H:i:s');

            $order->status = 1;

            $order->pay_type = 'money';

            if(empty($mix_pay_type)) $order->money = $order->pay_money;

            $order->save();

            if(!empty($mix_pay_type)){
                $return = mix_pay_money($order,'',3);
                if($return['error']){
                    Db::rollback();
                    return $this->error($return['error']);
                }
            }else {
                $res = $MemberWalletLogic->useBalance($needPay, $needPay, 25);

                if ($res == false) {
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }

            }
            //修改会员有效时间
            $return = memberVipTime($order);
            if(!$return['code']){
                return  $this->error($return['error']);
            }

            //领券
            memberVipCoupon($order,$level);

            Db::commit();

            return $this->success('储值卡支付成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }
}

